package com.heima.leetcode.practice;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author 勾新杰
 * @version 1.0
 * @description: leetcode 145. 二叉树的后序遍历
 * @date 2025/6/4 11:47
 */
public class E145 {

    /**
     * 方法一：递归
     *
     * @param root 树根结点
     * @return 节点值列表
     */
    public List<Integer> postorderTraversal1(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        postorderTraversal(root, result);
        return result;
    }

    /**
     * 递归
     *
     * @param root   树根结点
     * @param result 结果列表
     */
    private void postorderTraversal(TreeNode root, List<Integer> result) {
        if (root == null) return;
        postorderTraversal(root.left, result);
        postorderTraversal(root.right, result);
        result.add(root.val);
    }

    /**
     * 方法二：迭代
     *
     * @param root 树根结点
     * @return 节点值列表
     */
    public List<Integer> postorderTraversal2(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        LinkedList<TreeNode> stack = new LinkedList<>();
        TreeNode curr = root, lastPop = null;
        while (!stack.isEmpty() || curr != null) {
            if (curr != null) {
                stack.push(curr);
                curr = curr.left;
            } else {
                TreeNode last = stack.peek();
                if (last.right == null) {
                    stack.pop();
                    lastPop = last;
                    result.add(last.val);
                } else if (lastPop == last.right) {
                    stack.pop();
                    lastPop = last;
                    result.add(last.val);
                } else {
                    curr = last.right;
                }
            }
        }
        return result;
    }
}
